/*cond.c*/  
#include <pthread.h>  
#include <stdio.h>  
#include <stdlib.h>  
#include <unistd.h>  // 添加 sleep 头文件  

#define MAX 100  
pthread_mutex_t mutex;  
pthread_cond_t cond;  
int i = 1;  

void *thread1(void *flag) {  
    for (i = 1; i <= MAX; i++) {  
        pthread_mutex_lock(&mutex);  
        if (i % 9 == 0)  
            pthread_cond_signal(&cond);  
        else  
            printf("In thread1:%d\n", i);  
        pthread_mutex_unlock(&mutex);  
        sleep(1);  
    }  
    return NULL;  // 补充线程函数返回值  
}  

void *thread2(void *flag) {  
    while (i < MAX) {  
        pthread_mutex_lock(&mutex);  
        printf("In thread2 before wait\n");  
        if (i % 9 != 0)  
            pthread_cond_wait(&cond, &mutex);  
        printf("In thread2 after wait\n");  
        if (i % 9 == 0)  
            printf("In thread2:%d\n", i);  
        pthread_mutex_unlock(&mutex);  
        sleep(1);  
    }  
    return NULL;  // 补充线程函数返回值  
}  

int main() {  
    pthread_t t_a, t_b;  
    pthread_mutex_init(&mutex, NULL);  
    pthread_cond_init(&cond, NULL);  
    pthread_create(&t_a, NULL, thread2, NULL);  
    pthread_create(&t_b, NULL, thread1, NULL);  
    pthread_join(t_b, NULL);  
    pthread_mutex_destroy(&mutex);  
    pthread_cond_destroy(&cond);  
    return 0;  // 规范 main 函数返回值  
}  
